﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TianYu.Core.Common;
using TianYu.CMS.Service;
using Microsoft.AspNetCore.Http;
using TianYu.Core.Log;
using TianYu.CMS.Domain.DomainModel;

namespace TianYu.CMS.WebMvc.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class LoginController : Controller
    {
        private ISysUserService _sysUserService;
        private ISysLoginLogService _sysLoginLogService;
        private IHttpContextAccessor _accessor;

        public LoginController(ISysUserService sysUserService, ISysLoginLogService sysLoginLogService, IHttpContextAccessor accessor)
        {
            this._sysUserService = sysUserService;
            this._sysLoginLogService = sysLoginLogService;
            this._accessor = accessor;
        }



        public IActionResult Index()
        {
            bool isDebug = true;
#if !DEBUG
            isDebug = false;
#endif
            ViewBag.IsDebug = isDebug;
            return View();
        }
        public IActionResult LogOut()
        {
            var userName = HttpContext.Session.GetString("Admin_UserName");
            var trueName = HttpContext.Session.GetString("Admin_TrueName");
            Task.Run(() =>
            {
                _sysLoginLogService.InsertAsync(new SysLoginLog()
                {
                    ActionType = 2,
                    ExecResult = "退出成功",
                    ExecTime = DateTime.Now,
                    ExecIp = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(),
                    ExecContent = $"退出账号：{userName}； ",
                    Operator = userName
                });
            });

            HttpContext.Session.Clear();
            return Redirect("~/admin/login/index");
        }




        public async Task<AjaxResult<bool>> Login(string userName, string userPwd, string captcha)
        {
            string code = HttpContext.Session.GetString("Captcha");
            HttpContext.Session.Remove("Captcha");

            if (userName.IsNullOrEmpty())
            {
                return LoginResult(false, userName, "请输入用户名");
            }
            if (userPwd.IsNullOrEmpty())
            {
                return LoginResult(false, userName, "请输入密码");
            }
#if !DEBUG
            if (captcha.IsNullOrEmpty())
            {
                return LoginResult(false, userName, "请输入验证码");
            } 
            if (code.IsNullOrWhiteSpace())
            {
                return LoginResult(false, userName, "验证码失效");
            }
            if (!captcha.ToUpper().Equals(code.ToUpper()))
            {
                return LoginResult(false, userName, "输入的验证码错误");
            }
#endif

            var model = await _sysUserService.GetAsync(o => o.UserName == userName);
            if (model != null && model.Status == 0)
            {
                userPwd = EnDecrypt.SHA1Hash(userPwd + model.SaltValue);
                if (userPwd != model.UserPwd)
                {
                    return LoginResult(false, userName, "用户名或密码错误");
                }

                if (model.Enabled == Infrastructure.Enums.EnabledEnum.Enable)
                {
                    HttpContext.Session.SetString("Admin_UserId", model.Guid);
                    HttpContext.Session.SetString("Admin_UserName", model.UserName);
                    HttpContext.Session.SetString("Admin_TrueName", model.TrueName);
                }
                else
                {
                    return LoginResult(false, userName, "该账号已被禁用，请联系管理员");
                }
            }
            else
            {
                return LoginResult(false, userName, "用户名或密码错误");
            }

            return LoginResult(true, userName);
        }


        private AjaxResult<bool> LoginResult(bool res, string account, string message = "")
        {
            string errorMessage = string.Empty;
            if (!res)
            {
                errorMessage = $"；失败原因：{message}";
            }
            _sysLoginLogService.InsertAsync(new SysLoginLog()
            {
                ActionType = 1,
                ExecResult = res ? "登录成功" : $"登录失败{errorMessage}",
                ExecTime = DateTime.Now,
                ExecContent = "",
                ExecIp = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(),
                Operator = account
            });

            return res ? AjaxResult<bool>.Success() : AjaxResult<bool>.Fail(message);
        }
    }
}